<?php
namespace app\h5api\controller;

use app\common\model\Activity;
use app\common\model\Footprint;
use app\common\model\Collection;
use app\common\model\Settings;
use app\common\model\Signin;
use app\common\model\User;
use app\common\model\WinningRecord;
use app\common\service\Wechat;
use app\h5api\validate\Member;
use think\cache\driver\Redis;
use think\Exception;
use think\facade\Config;
use think\facade\Log;
use think\facade\Env;
use Upload;
use plug\SUtil;

class My extends Base
{
	/**
	 * @route('h5/GetUserAllInfo','get')
	 * 获取用户信息
	 */
	public function GetUserAllInfo()
	{
	    $userinfo = $this->GetUserInfo();
	    $signModel = new Signin();
        $where = [
            ['user_id','=',$userinfo['user_id']],
        ];
        $signinfo = $signModel->getOne($where);
        $userinfo['is_sign'] = 1;
        if(!empty($signinfo)){
            $userinfo['is_sign'] = 2;
        }
		$this->result(['data'=>$userinfo,'is_show_module'=>$this->is_show_module],1,'操作成功');
	}

	/**
	 * @route('h5/GetFootprintList','get')
	 * 个人足迹
	 */
	public function GetFootprintList()
	{
		$FootprintModel = new Footprint();
		$page = input('get.page') ? input('get.page') : 1;
		$list = $FootprintModel->GetDateList($this->_userid,$page);

		$this->result($list,1,'操作成功');
	}

	/**
	 * @route('h5/GetCollectionList','get')
	 * 个人收藏
	 */
	public function GetCollectionList()
	{
		$CollectionModel = new Collection();
		$type = input('get.type') ? input('get.type') : 1;
		$data = $CollectionModel->GetMyCollection($this->_userid,$type);

		$this->result($data,1,'操作成功');
	}

	/**
	 * @route('h5/DelCollections','post')
	 * 批量删除个人收藏
	 */
	public function DelCollections()
	{
		$ids = input('post.ids');
		$CollectionModel = new Collection();
		$res = $CollectionModel->Dels($this->_userid,$ids);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/UpdateUserInfo','post')
	 * 修改个人信息
	 */
	public function UpdateUserInfo()
	{
		$data = input('post.');
		$userModel = new User();
		$res = $userModel->allowField(['nick_name','real_name','phone'])->save($data, ['user_id' => $this->_userid]);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/UpdateAvatar','post')
	 * 修改个人头像
	 */
	public function UpdateAvatar()
	{
		$res = Upload::FileUpload('image','avatar',1024*1024*5,'jpg,jpeg,png');
		if(!$res['data']){
			$this->result([],-1,$res['msg']);
		}

		$userModel = new User();
		$res = $userModel->save(['avatar'=>$res['data']['file_path']], ['user_id' => $this->_userid]);
		if(!$res){
			$this->result([],-1,'操作失败');
		}
		$this->result([],1,'操作成功');
	}

	/**
	 * @route('h5/Share','post')
	 * 获取分享参数接口
	 */
	public function Share(){
		//将url拼接上分享参数
		$url = input('post.url','https://www.baidu.com');
		$data = input('post.data',[]);
		$data['from_id'] = $this->_userid;
		$srt = http_build_query($data);
		$share_url = $url.'?'.$srt;

		$jsapiTicket = Wechat::JsapiTicket();
		$nonceStr = SUtil::random(16);
		$timestamp = time();
		//注意！&timestamp会被转义成“xtamp”，将”&”换成”&amp;”
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);

		$return = [
			'signPackage' => [
				'appId'=>config::get('weixin.')['AppID'],
				'nonceStr'=>$nonceStr,
				'timestamp'=>$timestamp,
				'url'=>$url,
				'signature'=>$signature,
				'rawString'=>$string,
			],
			's' => $srt,
			'share_url' => $share_url,
		];
		$this->result($return,1,'操作成功');
	}

    /**
     * @route('h5/GetNormalQrCode','post')
     * 用户一般分享二维码
     */
    public function GetNormalQrCode() {
        $url = input('post.url');
        $url_data = parse_url($url);
        $get_query = [];
        if(isset($url_data['query'])){
            $query_data = explode('&',$url_data['query']);
            array_walk($query_data,function(&$v){ // 连接参数数组处理
                $data = explode('=',$v);
                $v = $data;
            });
            $key = array_column($query_data,'0');
            $value = array_column($query_data,'1');
            $get_query = array_combine($key,$value); // 键值数组合并
        }
//        var_dump($url_data);
        $userinfo = $this->GetUserInfo();
        $url = parse_url($url)['path'];
//        var_dump($code);die;
        $scene = [
            "from_uid" => $userinfo['user_id'],
        ];
        if(!empty($get_query)){
            $scene = array_merge($get_query,$scene); // 参数数组组合
        }
//        var_dump($scene);die;
        $wxconf = config::pull('weixin_applet');
        try{
            $path = Wechat::getwxacodeunlimit($wxconf,time(),$scene,'normalqrcode/',$url);
        } catch(\Exception $e){
//            echo $e->getMessage();
            $this->result([],-1,$e->getMessage());
        }
        if(!$path){
            $this->result([],-1,'创建二维码失败');
        }
        $this->result([
            'path' => $path
        ],1,'操作成功');
    }

    /**
     * @route('h5/UserApplyMember')
     * 用户申请会员
     */
    public function UserApplyMember()
    {
        $param = input('post.');
//        var_dump($param);die;
        $validate = new Member();
        $checkres = $validate->scene('member')->check($param);
        if (!$checkres) {
            $this->result('',-1,$validate->getError());
        }
        $userModel = new User();
        $where = [
            'user_id' => $this->_userid,
        ];
        $rs = $userModel->save(['utype'=>2],$where);
        if($rs === false){
            $this->result('',-1,$userModel->getError());
        }
        $this->result('',1,'操作成功');
    }

    /**
     * @route('h5/UserDraw')
     * 用户抽奖
     */
    public function UserDraw()
    {
        $userinfo = $this->_userInfo;
        $is_follow = false;
        if(!empty($userinfo['wx_openid'])){
            $is_follow = true;
//            $this->result([],1,'未关注微信公众号');
        }
        $now = time();
        $activityModel = new Activity();
        $condition = [
            ['begin_time','<',$now],
            ['end_time','>',$now],
            ['is_del','=',1],
        ];
        $activity = $activityModel->getOne($condition);
        if(empty($activity)){
            $this->result('',1,'暂无抽奖活动');
        }
        if(!$is_follow){
            $no_follow = [
                'activity_info' => $activity,
                'is_follow' => $is_follow,
            ];
            $this->result($no_follow, 1, '未关注只返回活动信息');
        }
        $redis = new Redis();
        $user_win_info = $redis->get("activity_{$activity['activity_id']}_{$this->_userid}");
        if(empty($user_win_info)) {
            $winModel = new WinningRecord();
            $win_record = $winModel->getOne([['user_id', '=', $this->_userid], ['is_del', '=', 1], ['activity_id', '=', $activity['activity_id']]], 'is_winning,winning_content,is_use');
            if (!empty($win_record)) {
                $win_record['activity_info'] = $activity;
                $win_record['is_follow'] = $is_follow;
                $redis->set("activity_{$activity['activity_id']}_{$this->_userid}", $win_record,60);
                $this->result($win_record, 1, '抽奖信息');
            }
            $settingModel = new Settings();
            $weight = $settingModel->get_list(['setg' => 'prize_draw'])->toArray();
//            var_dump($weight);die;
//            var_dump(array_column($weight, 'value'));die;
            $sum = array_sum(array_column($weight, 'value'));
            $rand = rand(0, $sum);
//            var_dump('随机：' . $rand);
            $ini_weight = 0;
            $is_winning = false;
            foreach ($weight as $value) {
                if ($rand < $ini_weight + $value['value']) {
//                    var_dump('权重：' . $value['value']);
//                    var_dump($ini_weight);
                    $value['key'] == 'success' ? $is_winning = true : '';
                    break;
                }
                $ini_weight += $value['value'];
            }

//            判断中奖人数是否已达发放奖品总数
            $winning_number = $winModel->where('is_winning','<>',1)->where('activity_id','=',$activity['activity_id'])->count();
            if($winning_number + 1 > $activity['provide_number']){
                $is_winning = false;
            }

//            var_dump($is_winning);die;
            $data = [
                'user_id' => $this->_userid,
                'activity_id' => $activity['activity_id'],
            ];
            $winning_content = '谢谢参与';
            if ($is_winning) {
//                var_dump($redis->get("activity_{$activity['activity_id']}"));
                $win_codes = empty($redis->get("activity_{$activity['activity_id']}")) ? [] : $redis->get("activity_{$activity['activity_id']}");
//                var_dump($win_codes);die;
                $number = $this->get_lucky_number($win_codes);
                array_push($win_codes, $number);
                $redis->set("activity_{$activity['activity_id']}", $win_codes);
//                var_dump($number);
//                var_dump($win_codes);die;
                $winning_content = $number;
            }
            $the_win_result = $is_winning ? 2 : 1;
            $data['winning_content'] = $winning_content;
            $data['is_winning'] = $the_win_result;
            $rs = $winModel->edit($data);
            if (!$rs) {
                $this->result([], -1, '抽奖记录写入失败');
            }
//            var_dump($data);die;
            $return['is_winning'] = $the_win_result;
            $return['is_use'] = 1;
            $return['winning_content'] = $winning_content;
            $return['activity_info'] = $activity;
            $redis->set("activity_{$activity['activity_id']}_{$this->_userid}", $return,60);
        } else {
            $return = $user_win_info;
        }
        $return['is_follow'] = $is_follow;
        $this->result($return,1,'操作成功');
    }

//    获取不重复幸运号码
    function get_lucky_number($lucky_list){
        $number = SUtil::random(6,1);
        if(in_array($number,$lucky_list)){
            return $this->get_lucky_number($lucky_list);
        }
        return $number;
    }

    /**
     * 用户关注公众号触发
     */
    public function followonwechat() {
//        return $_GET['echostr']; // 微信token验证（公众平台填写链接返回给微信验证）
        $testxml = file_get_contents("php://input");
        $this->recordlog("--------begin xml--------".$testxml."--------end xml--------",'info');
//        //将xml转化为json格式
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        //转成数组
        $result = json_decode($jsonxml, true);
//        var_dump($result);die;
        if($result['Event'] != 'subscribe'){
            return '';
        }
//        var_dump($result);die;
        $openid = $result['FromUserName'];
        //获取用户基本信息（包括UnionID机制）
        try{
            $UserInfo = Wechat::getuserinfo($openid);
        } catch(\Exception $e) {
            $this->recordlog("获取用户信息失败:{$e->getMessage()}",'error');
            $this->result([],-1,$e->getMessage());
        }
        $applet_config = config::pull('weixin_applet');
//        $str =  "<a data-miniprogram-appid='{$applet_config['AppID']}' data-miniprogram-path='pages/index/index'>点击跳小程序</a>";
        $image = "0T2bN6WtN3ae6J_mjgI8lfyy8biFIew1wVeXEjgdkJqV354bwUiUaDWqU7j6hC9X"; // 微信上传图片对应id
        $path = "pages/home/index?is_draw=1";
//        $title = "小灶派";
//        var_dump($UserInfo);die;
//        $senddata = [ // 单纯推送二维码
//            'touser' => $UserInfo['openid'],
//            'msgtype' => 'image',
//            "image" => [
//                "media_id" => $image,
//            ],
//        ];
        $senddata = [ // 推送小程序
            'touser' => $UserInfo['openid'],
            'msgtype' => 'miniprogrampage',
            "miniprogrampage" => [
//                "title" => $title,
                "appid" => $applet_config['AppID'],
                "pagepath" => $path,
                "thumb_media_id" => $image,
            ],
        ];
        try{
            Wechat::sendusermsg($senddata);
        }catch(\Exception $e){
            $this->recordlog("发送消息失败:{$e->getMessage()}",'error');
            $this->result([],-1,$e->getMessage());
        }
//        die;
//        var_dump($UserInfo);die;
        $userModel = new User();
        $user = $userModel->UnionidGetUser($UserInfo['unionid']);
        //查询该用户是否注册过
        if(!$user){//如果没注册过
            //新增用户
            $id = $userModel->binduser($UserInfo['nickname'],$UserInfo['sex'],$UserInfo['headimgurl'],$UserInfo['openid'],$UserInfo['unionid']);
            if(!$id){
                $this->recordlog("unionid：{$UserInfo['unionid']}新增操作失败",'error');
                $this->result([],-1,'新增操作失败');
            }
            //生成授权token
            return '';
        }

        $res = $userModel->login($user['user_id'],$UserInfo['openid'],'wx_openid');
        if(!$res){
            $this->recordlog("用户user_id：{$user['user_id']}操作失败",'error');
            $this->result([],-1,'更新操作失败');
        }
        return '';
    }

    private function recordlog($msg,$ltype){
        Log::init([
            'path' => Env::get('runtime_path')."followlog/",
        ]);
        Log::record($msg,$ltype);
    }
}
